package TankGame1;

import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Vector;

/**
 * 面板启动
 */
public class MyFrame extends JFrame {
    private MyPanel myPanel;
    private ObjectOutputStream oos;

    public static void main(String[] args) throws Exception {
        new MyFrame();
    }

    public MyFrame() throws Exception {
        int i=modelChoose();
        if (i==-1){
            System.exit(0); //程序退出
        }
        myPanel = new MyPanel(i);
        new Thread(myPanel).start();
        this.setSize(1300, 820);
        this.add(myPanel);
        this.addKeyListener(myPanel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        //监听关闭窗口事件
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                try {
                    Vector<EnemyTank> tanks = myPanel.getEnemyTanks();
                    for (int i = 0; i < tanks.size(); i++) {
                        tanks.get(i).getShots().clear();
                    }
                    //对象输出流
                    oos = new ObjectOutputStream(new FileOutputStream(new File(MyFrame.class.getResource("src/main/java/TankGame1/recorder1.txt").toURI())));
                    //将记录对象Recorder写到文件
                    oos.writeObject(myPanel.getRecorder());
                } catch (Exception e1) {
                    e1.printStackTrace();
                } finally {
                    if (oos != null) {
                        try {
                            oos.close();
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    public int modelChoose() {
        // 设置按钮字体大小
        UIManager.put("OptionPane.buttonFont", new FontUIResource(new Font("楷体", Font.BOLD, 25)));
        // 设置文本字体大小
        UIManager.put("OptionPane.messageFont", new FontUIResource(new Font("楷体", Font.BOLD, 30)));
        Object[] options = {"新游戏", "继续上局游戏"};
        int i = JOptionPane.showOptionDialog(null, "请选择开局方式？", "选择", JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, options, null);
        return i;
    }


}
